package com.icinfo.cloud.provider.common.zzd;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xxpt.gateway.shared.client.http.ExecutableClient;
import com.alibaba.xxpt.gateway.shared.client.http.GetClient;
import com.alibaba.xxpt.gateway.shared.client.http.PostClient;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 描述：executableClient要单例，并且使用前要初始化，只需要初始化一次.
 *
 * @author ZhangXiaoYan
 * @date 2021-08-02
 */
@Slf4j
@Component
public class DingDingApiUtil {
    private static Logger logger = LoggerFactory.getLogger(DingDingApiUtil.class);

    /**
     * 企业内应用免登-获取应用access_token
     */
    private static final String ACCESS_TOKEN_API = "/gettoken.json";
    /**
     * JSAPI鉴权
     */
    private static final String JSAPI_TOKEN_API = "/get_jsapi_token.json";
    /**
     * 环境域名
     */
    private static String domainName = "openplatform.dg-work.cn";

    private static String accessKey ="ZJHUIXIN-5q8y856n05RT3A6iaINzy";
    private static String secretKey = "7LxfsRnup9V64m52ysvvn5hAq96QUn9s03StumGW";
    /**
     * 使用volatile关键字防止重排序，因为 new Instance()是一个非原子操作，可能创建一个不完整的实例
     */
    private static volatile ExecutableClient executableClient;

    private DingDingApiUtil() {

    }

    public static ExecutableClient getClient(String accessKey, String secretKey, String domainName) {
        // Double-Check idiom
        if (executableClient == null) {
            synchronized (ExecutableClient.class) {
                // 只需在第一次创建实例时才同步
                if (executableClient == null) {
                    executableClient = ExecutableClient.getInstance();
                    executableClient.setAccessKey(accessKey);
                    executableClient.setSecretKey(secretKey);
                    executableClient.setDomainName(domainName);
                    executableClient.setProtocal("https");
                    executableClient.init();
                }
            }
        }
        return executableClient;
    }


     /**{"success":true,"content":{"data":{"expiresIn":7200,"accessToken":"app_776184fc97ce4453bef8c2e90f2d561d"},"success":true,"requestId":"276077df16505311754574498e43c5","responseMessage":"OK","responseCode":"0","bizErrorCode":"0"},"bizErrorCode":"0"}

      * @return
     * @author lxj
     * @date 2022-04-21
     */
    public static String getAccessToken() {
        ExecutableClient client = getClient(accessKey, secretKey, domainName);
        GetClient getClient = client.newGetClient(ACCESS_TOKEN_API);
        getClient.addParameter("appkey", accessKey);
        getClient.addParameter("appsecret", secretKey);
        String apiResult = getClient.get();
        logger.info("获取access_token接口返回结果:{}", apiResult);
        JSONObject obj = JSONObject.parseObject(apiResult);
        if(obj.getBoolean("success").booleanValue()){
            JSONObject ob = obj.getJSONObject("content");
            if(ob.getBoolean("success").booleanValue()){
               return  ob.getJSONObject("data").getString("accessToken");
            }
        }
        return "";
    }


    /**
     * 描述：JSAPI鉴权接口
     * API地址 https://openplatform-portal.dg-work.cn/backendManage/#/docs?apiType=serverapi&docKey=2674861
     * @return expiresIn 有效期，accessToken 鉴权ticket eg. data {"expiresIn":7199,"accessToken":"jsApi_9dbaff7f8b2a4b42ad27271892198298"}
     */
    public static String getJsapiToken() {
        String token = getAccessToken();
        // JSAPI鉴权API
        ExecutableClient client = DingDingApiUtil.getClient(accessKey, secretKey, domainName);
        PostClient postClient = client.newPostClient(JSAPI_TOKEN_API);
        // 设置参数- 应用 access_token
        postClient.addParameter("accessToken", token);
        //调用API
        String apiResult = postClient.post();
        //断开连接，释放资源
        client.destroy();
        logger.info("获取/get_jsapi_token.json接口返回结果=" + apiResult);
        JSONObject obj = JSONObject.parseObject(apiResult);
        if(obj.getBoolean("success").booleanValue()){
            JSONObject ob = obj.getJSONObject("content");
            if(ob.getBoolean("success").booleanValue()){
                return  ob.getJSONObject("data").getString("accessToken");
            }
        }

        return "";
    }

    /**
     * 描述：测试方法
     * @param args
     */
    public static void main(String[] args) throws Exception{

        System.out.println("apiResult========="+getJsapiToken());

    }

}
